#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/un.h>
#include <string.h>
#include <stddef.h>
#include <errno.h>


// struct sockaddr_un {
//     sa_family_t sun_family;               /* AF_UNIX */
//     char        sun_path[108];            /* pathname */
// };


static void err_sys(const char *str) {
    fprintf(stderr, "%s: %s\n", str, strerror(errno));
    exit(1);
}


/**
 * 将地址绑定到UNIX域套接字(UNIX Domain Socket)
 * 调用bind后, 系统会创建socket类型文件"foo.socket", 需要删除后, 才能再次运行程序
 */
int main() {
    int fd, size;
    struct sockaddr_un un;

    un.sun_family = AF_UNIX;
    strcpy(un.sun_path, "foo.socket");

    if ((fd = socket(un.sun_family, SOCK_STREAM, 0)) < 0) {
        err_sys("socket error");
    }

    size = offsetof(struct sockaddr_un, sun_path) + strlen(un.sun_path);
    if (bind(fd, (struct sockaddr *)&un, size) < 0) { 
        err_sys("bind error");
    }

    printf("UNIX domain socket bind success.\n");
    return 0;
}
